package com.youens.navigationdrawertest.ui.review

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import com.youens.navigationdrawertest.MainActivity
import com.youens.navigationdrawertest.R
import com.youens.navigationdrawertest.database.DataBaseUtils
import kotlinx.android.synthetic.main.fragment_blank.*

//暂时定义了Fragement的2个参数：翻译与单词
private const val ARG_PARAM1 = "word"
private const val ARG_PARAM2 = "translate"
private const val ARG_PARAM3 = "id"
private const val ARG_PARAM4 = "flag"

class BlankFragment : Fragment() {
    private var param1: String? = "word"
    private var param2: String? = "translate"
    private var param3: String? = "id"
    private var param4: Boolean = false
    private var listener: OnFragmentInteractionListener? = null
    private lateinit var buttonKnow:Button
    private lateinit var buttonNotKnow:Button
    private lateinit var buttonDim:Button
    private lateinit var buttonShowTranslate:Button
    private lateinit var databaseUtil:DataBaseUtils

    override fun onStart() {
        super.onStart()
        buttonKnow = view!!.findViewById(R.id.btn_know)
        buttonNotKnow = view!!.findViewById(R.id.btn_not_know)
        buttonDim = view!!.findViewById(R.id.btn_dim)
        buttonShowTranslate = view!!.findViewById(R.id.btn_show_translate)
        initListener()
    }

    /**
     * 从words表中随机know字段值为0（不认识）、1（模糊）的记录，而不取know为2（认识）的记录
     */
    private fun initListener(){
        buttonKnow.setOnClickListener {
            if (param4){
                databaseUtil.updateWrongWord(param3!!.toInt(),1,0)
                Toast.makeText(activity,"恭喜！",Toast.LENGTH_LONG).show()
            }else{
                databaseUtil.updateWordStatue(param3!!.toInt(),2)
                Toast.makeText(activity,"已学习！",Toast.LENGTH_LONG).show()
            }
        }

        buttonDim.setOnClickListener {
            if (param4){
                Toast.makeText(activity,"继续加油！",Toast.LENGTH_LONG).show()
            }else{
                databaseUtil.updateWordStatue(param3!!.toInt(),1)
                Toast.makeText(activity,"继续加油！",Toast.LENGTH_LONG).show()
            }

        }

        buttonNotKnow.setOnClickListener {
            if (param4){
                databaseUtil.updateWrongWord(param3!!.toInt(),0,1)
                Toast.makeText(activity,"很遗憾！",Toast.LENGTH_LONG).show()
            }else{
                databaseUtil.updateWordStatue(param3!!.toInt(),0)
                databaseUtil.addWrongWord(param3!!.toInt())
                Toast.makeText(activity,"仍需学习！",Toast.LENGTH_LONG).show()
            }
        }
        buttonShowTranslate.setOnClickListener {
            if (buttonShowTranslate.text.equals("显示翻译")){
                activity!!.runOnUiThread {
                    tran?.text = param2
                    buttonShowTranslate.text = "隐藏翻译"
                }
            }else{
                activity!!.runOnUiThread {
                    tran?.text = "---"
                    buttonShowTranslate.text = "显示翻译"
                }
            }

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        databaseUtil = (activity as MainActivity).getDataBaseUtils()
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
            param3 = it.getString(ARG_PARAM3)
            param4 = it.getString(ARG_PARAM4).toBoolean()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false)
    }
    //TODO 视图创建后，用传进来的单词，翻译，等其他文本更新ui
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        word?.text=param1
        tran?.text="---"
        Log.d("TAG","构建了一次视图：${word?.text} ${tran?.text}")
    }

    // TODO: 当需要点击按钮更改Fragement外的其容器内数据时使用（即Fragement与actity之间通信）
    fun onButtonPressed(uri: Uri) {
        listener?.onFragmentInteraction(uri)
    }
    // 实例化通信操作接口，不用改
    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnFragmentInteractionListener) {
            listener = context
        } else {
            throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")
        }
    }
    //销毁
    override fun onDetach() {
        super.onDetach()
        listener = null
    }
    //TODO 父容器需扩展此接口并实现
    interface OnFragmentInteractionListener {
        // TODO: 当点击按钮更改Fragement外的其容器内数据时的具体操作

        fun onFragmentInteraction(uri: Uri)
    }

    companion object {
        @JvmStatic
        fun newInstance(id:Int, result: String, translate: String,flag: Boolean) =
            BlankFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, result)
                    putString(ARG_PARAM2, translate)
                    putString(ARG_PARAM3, id.toString())
                    putString(ARG_PARAM4, flag.toString())
                }
            }
    }
}
